package proxy;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.Date;

import message.response.MessageResponse;

public class FsListener extends Thread {

	private Proxy proxy;
	private boolean listening;

	private DatagramSocket socket;
	private DatagramPacket packet;

	public FsListener(Proxy proxy) {
		super("FileserverListenerThread");

		this.proxy = proxy;

		try {
			socket = new DatagramSocket(this.proxy.getUdpPort());
		} catch (SocketException e) {
			System.out.println(new MessageResponse("Error: An unexpected error occurred!"));
		}
	}

	@Override
	public void run() {
		listening = true;

		String aliveMessage;
		int tcpPort;

		while (listening) {
			byte[] buf = new byte[256];
			packet = new DatagramPacket(buf, buf.length);

			try {
				socket.receive(packet);
			} catch (SocketException e) {
				// Gets thrown on shutdown so -> Ignore
			} catch (IOException e) {
				System.out.println(new MessageResponse("Error: An unexpected error occurred!"));
			}

			aliveMessage = new String(buf);

			/*
			 * Check if message is an alive message as expected
			 */
			if (aliveMessage.trim().matches("^!alive(\\s)(\\d{1,5})$")) {
				/*
				 * Split message on whitespaces and take the second part.
				 */
				String messageParts[] = aliveMessage.split("\\s");

				if (messageParts.length > 1) {
					String tcpPortS = messageParts[1].trim();
					tcpPort = Integer.parseInt(tcpPortS);

					proxy.updateFileservers(packet.getAddress(), tcpPort,
							new Date().getTime());
				}
			}
			/*
			 * Else alive message did not match pattern. 
			 */
		}
	}

	public void shutdown() {
		listening = false;
		if (socket != null && !socket.isClosed())
			socket.close();
	}

}
